package com.shundr.user;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.common.http.CommonRequest;
import com.shundr.common.model.PictureInfo;
import com.shundr.common.util.Base64Util;
import com.shundr.common.util.JsonUtil;
import com.shundr.common.util.PictureUtil;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.frame.constant.LConstants;
import com.shundr.frame.util.LLogger;
import com.shundr.frame.util.StringUtil;
import com.shundr.user.http.UserRequest;
import com.shundr.user.model.UserInfo;
import com.shundr.user.util.UserUtil;

public class UserInfoActivity extends BaseActivity implements OnClickListener {

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";
	
	private ImageView ivHeadPic;
	private TextView tvName;
	private TextView tvPhone;
	private TextView tvIntegral;
	private ImageView ivAuthStatus;

	private RelativeLayout mLayoutUserHead;
	private RelativeLayout mLayoutNoName;
	private RelativeLayout mLayoutNoAuth;
	private LinearLayout mLayoutUserInfo;
	private RelativeLayout mLayoutUserPhone;
	private RelativeLayout mLayoutIntegral;
	private int authStatus;
	
	private DisplayImageOptions mOptions;
	
	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();
	
	private UserInfo mUserInfo;
	
	@SuppressLint("HandlerLeak")
	Handler mHandler=new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserRequest.GET_USER_DETAIL_INFO_SUCCESSED:
					mUserInfo = (UserInfo) msg.obj;
					UserUtil.saveUserToLocal(mContext, mUserInfo, null);
					showUserInfo(mUserInfo);
					mLayoutUserInfo.setVisibility(View.VISIBLE);
					ProgressDialogHelper.dismiss();	
					break;
				case UserRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();	
					String description=(String)msg.obj;
					ToastHelper.toastShort(mContext, description);
					break;
				case UserRequest.COMMIT_USER_HEAD_SUCCESSED:
					ToastHelper.toastShort(mContext, "头像上传成功");
					new UserRequest(mContext, mHandler).getUserInfoByToken();
					break;
				case UserRequest.GET_INTEGRAL_TOTAL_SUCCESSED:
					tvIntegral.setText(msg.obj.toString());
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
	};
	
	/**
	 * 退出登录
	 */
	private Button btnLogout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_info);

		mLayoutUserHead = (RelativeLayout)findViewById(R.id.layout_head);
		mLayoutUserPhone=(RelativeLayout)findViewById(R.id.layout_user_phone);
		mLayoutIntegral = (RelativeLayout)findViewById(R.id.layout_integral);
		mLayoutUserInfo=(LinearLayout)findViewById(R.id.activity_user_info);
		ivHeadPic = (ImageView) findViewById(R.id.iv_user_info_portrait);
		tvName = (TextView) findViewById(R.id.tv_user_info_username);
		tvPhone = (TextView) findViewById(R.id.tv_user_info_phone);
		tvIntegral = (TextView)findViewById(R.id.tv_integral);
		ivAuthStatus = (ImageView) findViewById(R.id.tv_user_info_certification_status);
		mLayoutNoName = (RelativeLayout) findViewById(R.id.ll_add_name);
		mLayoutNoAuth = (RelativeLayout) findViewById(R.id.ll_data_to_renzheng);
		btnLogout = (Button) findViewById(R.id.btn_logout);
		btnLogout.setOnClickListener(this);
		mLayoutNoAuth.setOnClickListener(this);
		mLayoutUserHead.setOnClickListener(this);
		mLayoutUserPhone.setOnClickListener(this);
		mLayoutIntegral.setOnClickListener(this);
		ivHeadPic.setOnClickListener(this);
//		mLayoutNoName.setOnClickListener(this);
//		mLayoutUserPhone.setOnClickListener(this);
		initOptions();
		ProgressDialogHelper.show(mContext, "正在加载中...");
//		new UserRequest(mContext, mHandler).getUserInfoByToken();
	}
	
	@Override
	protected void onResume() {
		new UserRequest(mContext, mHandler).getUserInfoByToken();
		new UserRequest(mContext, mHandler).getCreditsTotal();
		super.onResume();
	}

	/**
	 * 显示
	 * 
	 * @param info
	 */
	private void showUserInfo(UserInfo info) {
		if (info != null) {
			try {
				String name = info.getUserName();
				if (name != null) {
					tvName.setText(name);
				}
				String phone = info.getUserPhone();
				if (phone != null) {
					tvPhone.setText(phone);
				}
				authStatus = info.getIdValidationStatus();
				switch (authStatus) {
				case 0:ivAuthStatus.setImageResource(R.drawable.ic_auth_no);
					break;
				case 1:ivAuthStatus.setImageResource(R.drawable.ic_auth_ing);
					break;
				case 2:ivAuthStatus.setImageResource(R.drawable.ic_auth_ok);
					break;
				case 3:ivAuthStatus.setImageResource(R.drawable.ic_auth_fail);
					break;
				default:
					break;
				}
				String headUrl=info.getUserHeadPic();
				ImageLoader.getInstance().displayImage(headUrl, ivHeadPic,mOptions);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.iv_user_info_portrait:
			try {
				if(!StringUtil.isNull(mUserInfo.getUserHeadPic())){
					ArrayList<String> list = new ArrayList<String>();
					if(!StringUtil.isNull(mUserInfo.getUserHeadPic())){
						list.add(mUserInfo.getUserHeadPic());
					}
					if(list.size() > 0){
						openImageReview(mContext, 0, list);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.layout_head:
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.layout_user_phone:
			startActivity(new Intent(mContext, ChangePhoneActivity.class));
			break;
		case R.id.layout_integral:
			startActivity(new Intent(mContext, CreditsActivity.class));
			break;
		case R.id.ll_data_to_renzheng:
			if(authStatus==0){
				intent = new Intent(mContext, UserAuthActivity.class);
				startActivityForResult(intent, 333);
			}else if(authStatus==1){
//				ToastHelper.toastShort(mContext, "您的认证信息正在审核中");
				startActivityForResult(new Intent(mContext, UserReAuthActivity.class), 333);
			}else if(authStatus==2){
				startActivityForResult(new Intent(mContext, UserReAuthActivity.class), 333);
			}else if(authStatus==3){
				startActivityForResult(new Intent(mContext, UserReAuthActivity.class), 333);
			}
			break;	
		case R.id.btn_logout:
			UserUtil.logout(mContext);
			new CommonRequest(mContext, new Handler()).saveAppOperate(2);
			finish();
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			Uri data2 = null;
			if (data == null) {
				data2 = PictureUtil.getImageUri();
			} else {
				data2 = data.getData();
			}
			String outPic = "";
			if (resultCode == RESULT_OK) {
				switch (requestCode) {
				case PictureUtil.PHOTO_PICKED_WITH_DATA:
					outPic = PictureUtil.getRealFilePath(mContext, data2);
					outPic = PictureUtil.compressJpgImage(outPic);
					if (!new File(outPic).exists()) {
						ToastHelper.toastShort(mContext, getResources().getString(R.string.image_error));
						return;
					}
					
					Bitmap bitmap = BitmapFactory.decodeFile(outPic);
					PictureInfo info = new PictureInfo();
					info.setFileBase64Body(Base64Util.encodeImage(bitmap));
					info.setFilename(outPic);
					bitmap.recycle();
					info.setType(PictureInfo.FileType.head);
					mPictures.add(info);
					String json = JsonUtil.toJson(mPictures);
					LLogger.e(json);
					ProgressDialogHelper.show(mContext, "上传头像...");
					new UserRequest(mContext, mHandler).commitUserHead(json);
					break;
				case PictureUtil.CAMERA_WITH_DATA:
					outPic = PictureUtil.compressJpgImage(LConstants.TEMP_PIC_PATH);
					if (!new File(outPic).exists()) {
						ToastHelper.toastShort(mContext, getResources().getString(R.string.image_error));
						return;
					}
					
					Bitmap bitmap1 = BitmapFactory.decodeFile(outPic);
					PictureInfo info1 = new PictureInfo();
					info1.setFileBase64Body(Base64Util.encodeImage(bitmap1));
					info1.setFilename(outPic);
					bitmap1.recycle();
					info1.setType(PictureInfo.FileType.head);
					mPictures.add(info1);
					String json1 = JsonUtil.toJson(mPictures);
					LLogger.e(json1);
					ProgressDialogHelper.show(mContext, "上传头像...");
					new UserRequest(mContext, mHandler).commitUserHead(json1);
					break;
				case PictureUtil.PHOTO_CROP:
					break;
				case 501:
					new UserRequest(mContext, mHandler).getUserInfoByToken();
					break;
				default:
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void initOptions(){
		mOptions = new DisplayImageOptions.Builder()  
		.showImageForEmptyUri(R.drawable.iv_head)//设置图片Uri为空或是错误的时候显示的图片  
		.showImageOnFail(R.drawable.iv_head)  
		.cacheInMemory(true) //设置图片加载/解码过程中错误时候显示的图片  
		.cacheInMemory(true)//设置下载的图片是否缓存在内存中  
		.cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中  
		.considerExifParams(true)  
		.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示  
		.bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//  
//		.decodingOptions(Options decodingOptions)//设置图片的解码配置  
		.considerExifParams(true)//设置图片下载前的延迟  
		//.delayBeforeLoading(int delayInMillis)//int delayInMillis为你设置的延迟时间  
		//设置图片加入缓存前，对bitmap进行设置  
		//.preProcessor(BitmapProcessor preProcessor)  
//		.resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位  
		.displayer(new RoundedBitmapDisplayer(45))//是否设置为圆角，弧度为多少  
//		.displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间  
		.build();//构建完成  
	}
}
